'use strict';
(function(){
  const KEY='palette_recent_colors_v2', MAX=16;
  function toHex(el){
    const c=el.getAttribute('data-hex')||el.getAttribute('data-color')||el.getAttribute('data-swatch'); if(c) return c.startsWith('#')?c.toUpperCase():('#'+c.toUpperCase());
    const sw=el.style.getPropertyValue('--sw'); if(sw) return sw.startsWith('#')?sw.toUpperCase():('#'+sw.toUpperCase());
    const m=getComputedStyle(el).backgroundColor.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/); if(!m) return null; const to=v=>parseInt(v,10).toString(16).padStart(2,'0'); return `#${to(m[1])}${to(m[2])}${to(m[3])}`.toUpperCase();
  }
  function load(){ try{return JSON.parse(localStorage.getItem(KEY)||'[]');}catch(e){return[];} }
  function save(arr){ try{localStorage.setItem(KEY, JSON.stringify(arr));}
  function uniqueHex(arr){
    const out=[]; const seen=new Set();
    arr.forEach(h=>{ if(!h) return; h=h.toUpperCase(); if(h[0]!=='#') h='#'+h; if(!/^#[0-9A-F]{6}$/.test(h)) return; if(!seen.has(h)){ seen.add(h); out.push(h);} });
    return out;
  }
  function gridHexSet(root){
    const set=new Set();
    root.querySelectorAll('.cb-grid .swatch,[data-hex],[data-swatch],[data-color]').forEach(el=>{
      let h=el.getAttribute('data-hex')||el.getAttribute('data-color')||el.getAttribute('data-swatch')||el.style.getPropertyValue('--sw');
      if(!h){
        const bg=getComputedStyle(el).backgroundColor;
        const m=bg&&bg.match(/rgba?\((\d+),(\d+),(\d+)/);
        if(m){ const h2=(v)=>('0'+Number(v).toString(16)).slice(-2).toUpperCase(); h='#'+h2(m[1])+h2(m[2])+h2(m[3]); }
      }
      if(h){ h=h.toUpperCase(); if(h[0]!=='#') h='#'+h; if(/^#[0-9A-F]{6}$/.test(h)) set.add(h); }
    });
    return set;
  }
catch(e){} }
  function push(hex){
      if(!hex) return load();
      hex = hex.toUpperCase(); if(hex[0]!=='#') hex='#'+hex;
      let list = uniqueHex([hex].concat(load()));
      const MAX=16; while(list.length>MAX) list.pop();
      save(list); return list;
    }$/i.test(hex)) return load(); hex=hex.startsWith('#')?hex.toUpperCase():('#'+hex.toUpperCase()); const list=load().filter(x=>x&&x.toUpperCase()!==hex); list.unshift(hex); while(list.length>MAX) list.pop(); save(list); return list; }
  function ensureContainer(root){ let wrap=root.querySelector('.cb-recent'); if(!wrap){ wrap=document.createElement('div'); wrap.className='cb-recent'; wrap.innerHTML='<span class="label">最近使用</span>'; const grid=root.querySelector('.cb-grid'); if(grid&&grid.parentNode) grid.parentNode.appendChild(wrap); else root.appendChild(wrap);} return wrap; }
  function applyToUI(root, hex){ const prev=root.querySelector('.cb-selected .swatch'); if(prev){ prev.style.setProperty('--sw', hex); prev.style.background=hex; } const val=root.querySelector('.cb-selected .value, .cb-selected .hex, .cb-selected .code'); if(val){ val.textContent=hex; } const input=root.querySelector('#color-input, input[name=\"color\"], input[data-color-input], input[type=\"color\"], input.color-hex'); if(input){ try{ input.value=hex; input.dispatchEvent(new Event('input',{bubbles:true})); input.dispatchEvent(new Event('change',{bubbles:true})); }catch(e){} } root.dispatchEvent(new CustomEvent('palette:color-picked',{detail:{hex}})); }
  function render(root){
      const wrap=ensureContainer(root);
      const list=load();
      const gridSet=gridHexSet(root);
      const filtered=list.filter(h=>!gridSet.has(h.toUpperCase()));
      wrap.innerHTML='';
      filtered.forEach(hex=>{
        const chip=document.createElement('button');
        chip.className='color-chip'; chip.type='button'; chip.setAttribute('data-hex', hex);
        chip.innerHTML=`<span class="swatch" style="--sw:${hex}"></span><span class="hex">${hex}</span>`;
        chip.addEventListener('click', e=>{ e.preventDefault(); applyToUI(root, hex); });
        wrap.appendChild(chip);
      });
    } }); wrap.appendChild(chip); }); }
  function wire(root){ root.addEventListener('click', e=>{ const sw=e.target.closest('.swatch'); if(!sw) return; const hex=toHex(sw); if(!hex) return; push(hex); render(root); }); }
  function boot(){ const sections=document.querySelectorAll('#color-search, #color-board, #tp-colorboard'); if(!sections.length) return; sections.forEach(root=>{ ensureContainer(root); wire(root); render(root); }); }
  document.addEventListener('DOMContentLoaded', boot); window.addEventListener('load', boot);
})();
